import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * EmbeddedChannel 快捷测试
 *
 * @author ganbo
 * @date 2022/12/7 21:23
 */

@Slf4j
public class EmbeddedChannelTest3 {

    public static void main(String[] args) {

        //添加handler并且活的channel
        EmbeddedChannel channel = new EmbeddedChannel(
                //这里长度字节是4，所以最后一个参数剥离长度设置为4
                new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4),
                new LoggingHandler(LogLevel.DEBUG),
                new StringDecoder(),
                new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                        ByteBuf buf = (ByteBuf) msg;
                        System.out.println("=============>" + msg);
                    }
                });


        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        buildSend(byteBuf, "Hello world");
        buildSend(byteBuf, "Hi");
        buildSend(byteBuf, "你好 netty！！！");

//        //模拟入栈操作
        channel.writeInbound(byteBuf);

        System.out.println("发送完毕....");
    }

    private static void buildSend(ByteBuf buf, String content) {
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        buf.writeInt(bytes.length + 1); //长度
        buf.writeByte(97);           //版本
        buf.writeBytes(bytes);      //内容
    }

    @Test
    public void t1() {
        char a = 'a';
        System.out.println((int) a);
    }
}
